package com.omg.weibo;


import java.io.InputStreamReader;
import java.io.Reader;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.Source;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.util.EntityUtils;

public class GetQQAcessToken {
	private static final Log log = LogFactory.getLog(GetQQAcessToken.class);
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String requestUrl = "https://open.t.qq.com/cgi-bin/oauth2/authorize?client_id=801130889&response_type=token&redirect_uri=http%3A%2F%2Fwww.buymefan.com%2F";
		System.out.println(getTokenInfo(requestUrl, "buymefan@126.com", "bmf_admin"));

	}
	
	public static String getTokenInfo(String requestUrl, String uin, String p) {
		String userAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; InfoPath.2; staticlogin:product=cboxf2010&act=login&info=ZmlsZW5hbWU9UG93ZXJXb3JkMjAxME94Zl9VbHRpbWF0ZS5leGUmbWFjPTU2ODE4RkIyMDYyNzQyNkY4RTExRkU5OUVDNEE5RDM3JnBhc3Nwb3J0PSZ2ZXJzaW9uPTIwMTAuNi4zLjYuMiZjcmFzaHR5cGU9MQ==&verify=068db92448c991d3ade2b957d10041f1)";
		DefaultHttpClient client = new DefaultHttpClient(new ThreadSafeClientConnManager());
        //client.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 5000);
        String tokenInfo = "";
        HttpGet get = null;
        try {
			//String requestUrl = "https://open.t.qq.com/cgi-bin/oauth2/authorize?client_id=801130889&response_type=token&redirect_uri=http%3A%2F%2Fwww.buymefan.com%2F";
			get = new HttpGet(requestUrl);
			get.setHeader("Host", "open.t.qq.com");
			HttpResponse response = client.execute(get);
			String entity = EntityUtils.toString(response.getEntity());
			CookieStore cookiestore = client.getCookieStore();
			Source source = new Source(entity);
			Element el = source.getElementById("u1");
			String u1 = el.getAttributeValue("value");
			String u2 = u1;
			u1 = u1.replaceAll("://", "%3A%2F%2F");
			
			/********************* 获取验证码 ***********************/
			get = new HttpGet("https://ssl.ptlogin2.qq.com/check?uin="+ uin + "&appid=46000101&ptlang=2052&r=" + Math.random());
			get.setHeader("Host", "check.ptlogin2.qq.com");
			get.setHeader("Referer", requestUrl);
			get.setHeader("User-Agent",userAgent);
			response = client.execute(get);
			cookiestore = client.getCookieStore();

			entity = EntityUtils.toString(response.getEntity());
			String[] checkNum = entity.substring(entity.indexOf("(") + 1,entity.lastIndexOf(")")).replace("'", "").split(",");
			//System.out.println(checkNum[0]);
			//System.out.println(checkNum[1]);
			//System.out.println(checkNum[2].trim());
			//System.out.println(checkNum[2].trim().replace("\\x", ""));
			String pass = "";

			/******************** *加密密码 ***************************/
			ScriptEngineManager manager = new ScriptEngineManager();
			ScriptEngine engine = manager.getEngineByName("javascript");

			String jsFileName = "md52.js"; // 指定md5加密文件
			// 读取js文件
			//FileReader reader = new FileReader(jsFileName);
			Reader reader = new InputStreamReader(GetQQAcessToken.class.getClassLoader().getResource(jsFileName).openStream());
			engine.eval(reader);

			if (engine instanceof Invocable) {
				Invocable invoke = (Invocable) engine;
				// 调用preprocess方法，并传入两个参数密码和验证码
				pass = invoke.invokeFunction("QXWEncodePwd",checkNum[2].trim(), p, checkNum[1].trim()).toString();
				//System.out.println("c = " + pass);
			}
			reader.close();

			/************************* 登录 ****************************/
			String loginUrl = "https://ssl.ptlogin2.qq.com/login?ptlang=2052&u="
					+ uin
					+ "&p="
					+ pass
					+ "&verifycode="
					+ checkNum[1]
					+ "&aid=46000101&u1="+u1
					+"&fp=loginerroralert&action=2-10-9063&g=1&t=1&h=1&dumy=&dummy=&ptredirect=1&from_ui=1&target=top&wording=快速登录";
			get = new HttpGet(loginUrl);
			get.setHeader("Connection", "Keep-Alive");
			get.setHeader("Host", "ssl.ptlogin2.qq.com");  
			get.setHeader("Referer", requestUrl);
			get.setHeader("User-Agent",userAgent);
			client.setCookieStore(cookiestore);
			response = client.execute(get);
			cookiestore = client.getCookieStore();
			entity = EntityUtils.toString(response.getEntity(), "UTF-8");
			//System.out.println(entity);
			if (null != entity && entity.indexOf("登录成功") > 0){
				/****获取返回的access_token地址***/
				get = new HttpGet(u2);
				get.setHeader("Connection", "Keep-Alive");
				get.setHeader("Host", "open.t.qq.com");  
				get.setHeader("User-Agent", userAgent);
				client.setCookieStore(cookiestore);
				response = client.execute(get);
				entity = EntityUtils.toString(response.getEntity(), "UTF-8");
				if (null != entity){
					source = new Source(entity);
					el = source.getFirstElement(HTMLElementName.META);
					String tokenUrl = el.getAttributeValue("content");
					if(null != tokenUrl){
						int index = tokenUrl.indexOf("#");
						if (index > -1){
							tokenInfo = tokenUrl.substring(index+1);
						}
					}
				}
			}

		} 
        catch (Exception e) {
			log.error(e);
		}
        finally{
        	//if (null != get)
        	   //get.releaseConnection();
        }
        return tokenInfo;
	}
}